<?php
Abstract class MysqlModel extends Zend_Db_Table_Abstract
{

    private $mysql = null;
    protected $filesystem = null;
    protected $_redis = null;
    private static $DB_EXCEP_LOG_ON = true;  //是否开启日志

    public function __construct()
    {
        $this->mysql = Yaf_Registry::get('mysql');
        parent::__construct($this->mysql);
    }



    /**
     * DB异常日志
     */
    public function logException($string){
        if(empty($string)){
            $string = 'null';
        }
        $curtime = time();
        if(self::$DB_EXCEP_LOG_ON){
            $fopen = fopen('/data/bak/log/db_exception.log', 'a');
            if($fopen){
                $string = date("Y-m-d H:i:s", $curtime) . '  ==> ' . $string;
                fwrite($fopen, $string . "\n");
                fclose($fopen);
            }
        }
    }

    public function getConnectionId() {
        $sql = "SELECT CONNECTION_ID() as conn_id";
        return $this->_db->fetchRow($sql);
    }
    public function beginTransaction() {
        return $this->_db->beginTransaction();
    }
    public function commit() {
        return $this->_db->commit();
    }
    public function rollBack() {
        return $this->_db->rollBack();
    }

    public function addPic($upload_file = 'upload_file', $remote_pic = '')
    {
        if(empty($remote_pic)){
            $ext_name = substr(strrchr($_FILES[$upload_file]['name'], '.'), 1);
            $remote_pic = time() . rand(1000, 9999) . '.' . $ext_name;
        }
        return $this->uploadQiniu($upload_file, $remote_pic);
    }

    #图片上传到七牛
    public function uploadQiniu($upload_file = 'upload_file', $remote_pic = ''){

        if(isset($_FILES[$upload_file]) && $_FILES[$upload_file]['error'] == 0 ){
            $ext_name = substr(strrchr($_FILES[$upload_file]['name'],'.'),1);
            try{
                $cloud_obj = new CloudFileSystem();
                if(empty($remote_pic)) {
                    $remote_pic = uniqid(rand(), true).".".$ext_name;
                }
                if(isset($_FILES[$upload_file])){
                    $flag = $cloud_obj->upload($upload_file,$remote_pic);
                    if($flag) {
                        return $remote_pic;
                    } else {
                        return false;
                    }
                }
            }catch(Exception $ex){
                $this->logException($ex->getMessage());
                return false;
            }
        }else{
            return "";
        }
    }


    public static function createClass($className)
    {
        $class_model = '';
        if(class_exists($className)){
            $class_model = new $className();
        }
        return $class_model;
    }


}
